#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include "/home/lhr/http-server/dbManager.hpp"
#include "/home/lhr/http-server/Util.hpp"

Json::Value result;
DBManager &db = DBManager::GetInstance();

// article_id=90&content=11
void ProcessComment()
{
    std::string reqParam;
    Util::GetReqParam(reqParam);

    std::string str1;
    std::string str2;
    Util::CutString(reqParam, str1, str2, "&");

    std::string article_ID;
    std::string article_id;
    Util::CutString(str1, article_ID, article_id, "=");
    int articleID = std::stoi(article_id);

    std::string Content;
    std::string content;
    Util::CutString(str2, Content, content, "=");
    content = Util::UrlDecode(content);

    std::string session_token = getenv("SESSION_TOKEN");

    // 根据session_token获取用户ID
    int userId = 0;
    int ret = db.GetUserIdByToken(session_token, userId);
    if (ret != SUCCESS)
    {
        result["success"] = false;
        result["message"] = "获取用户ID失败";
        return;
    }

    ret = db.addComment(articleID, userId, content);
    if (ret != SUCCESS)
    {
        result["success"] = false;
        result["message"] = "评论提交失败";
        return;
    }

    result["success"] = true;
    result["message"] = "评论成功";
}
int main()
{
    ProcessComment();

    std::string http_resBody = result.toStyledString();
    std::string http_res = "HTTP/1.0 200 OK\r\n";
    http_res += "Content-Type: application/json\r\n";
    http_res += "Content-Length: " + std::to_string(http_resBody.length()) + "\r\n\r\n";
    http_res += http_resBody;

    std::cout << http_res;
    return 0;
}
